package com.qut.graduate.busrtquery.presenter;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qut.graduate.busrtquery.BRTQConstant;
import com.qut.graduate.busrtquery.R;
import com.qut.graduate.busrtquery.bean.User;
import com.qut.graduate.busrtquery.ui.user.LoginActivity;
import com.qut.graduate.busrtquery.ui.user.UserCenterActivity;
import com.qut.graduate.busrtquery.utils.common.FormatUtils;
import com.qut.graduate.busrtquery.utils.common.LogUtils;
import com.qut.graduate.busrtquery.utils.uiabout.ToastColorfulUtils;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import top.wefor.circularanim.CircularAnim;

/**
 * 登录界面逻辑
 *
 * @Author WLL
 * @Time: 2019/3/28 9:45
 */
public class LoginPresenter {

    private static final String TAG = "LoginPresenter";

    private LoginActivity loginActivity;

    public LoginPresenter(LoginActivity loginActivity) {
        this.loginActivity = loginActivity;
    }

    public OnRegisterListener listener;

    public void SetOnRegisterListener(OnRegisterListener listener) {
        this.listener = listener;
    }

    public interface OnRegisterListener {
        void OnFinish();

        void OnFail();
    }

    public void login(int type, final String username, final String email, final String pwd,
                      final Button login, final ProgressBar progressbar) {
        if (type == BRTQConstant.LOGIN_LAYOUT_LOGIN_EMAIL) {
            if (email != null && (!FormatUtils.isEmail(email) || email.length() > 31)) {
                ToastColorfulUtils.error("邮箱格式错误");
                setViewVisible(login, progressbar);
                return;
            }
        }
        if (type == BRTQConstant.LOGIN_LAYOUT_LOGIN) {
            if (username != null && !FormatUtils.isUserName(username)) {
                ToastColorfulUtils.error("用户名应为3-12个数字、字母或汉字");
                setViewVisible(login, progressbar);
                return;
            }
        }
        if (pwd != null && pwd.length() < 6) {
            ToastColorfulUtils.error("密码应为6-12个数字或字母");
            setViewVisible(login, progressbar);
            return;
        }

        if (type == BRTQConstant.LOGIN_LAYOUT_LOGIN) {
            // 用户名登录
            BmobQuery<User> query = new BmobQuery<User>();
            query.addWhereEqualTo("username", username);
            query.findObjects(new FindListener<User>() {
                @Override
                public void done(List<User> object, BmobException e) {
                    progressbar.setVisibility(View.GONE);
                    login.setVisibility(View.VISIBLE);
                    if (e == null && null != object && object.size() != 0) {
                        LogUtils.d("----登录注册Presenter  用户存在", this.getClass());
                        ToastColorfulUtils.info("用户存在");
                        User user = new User();
                        user.setUsername(username);
                        user.setPassword(pwd);
                        user.login(new SaveListener<User>() {
                            @Override
                            public void done(User user, BmobException e) {
                                if (user != null && e == null) {
                                    LogUtils.d("----登录注册Presenter  用户名登录成功", this.getClass());
                                    ToastColorfulUtils.success("登录成功");
                                    startToUserCenter(login, progressbar);
                                } else {
                                    LogUtils.d("----登录注册Presenter  用户名登录失败" + String.valueOf(e), this.getClass());
                                    ToastColorfulUtils.error("登录失败,请重新登录");
                                }
                            }
                        });
                    } else {
                        LogUtils.d("----登录注册Presenter  用户名登录失败" + String.valueOf(e), this.getClass());
                        ToastColorfulUtils.info("用户不存在,请先注册");
                    }
                }
            });
        } else if (type == BRTQConstant.LOGIN_LAYOUT_LOGIN_EMAIL) {
            // 邮箱登录
            BmobQuery<User> query = new BmobQuery<User>();
            query.addWhereEqualTo("email", email);
            query.findObjects(new FindListener<User>() {
                @Override
                public void done(List<User> object, BmobException e) {
                    progressbar.setVisibility(View.GONE);
                    login.setVisibility(View.VISIBLE);
                    if (e == null && null != object && object.size() != 0) {
                        LogUtils.d("----登录注册Presenter  邮箱存在", this.getClass());
                        ToastColorfulUtils.info("邮箱存在");
                        BmobUser.loginByAccount(email, pwd, new LogInListener<User>() {
                            @Override
                            public void done(User user, BmobException e) {
                                if (user != null && e == null) {
                                    LogUtils.d("----登录注册Presenter  邮箱登录成功", this.getClass());
                                    ToastColorfulUtils.success("登录成功");
                                    startToUserCenter(login, progressbar);
                                } else {
                                    LogUtils.d("----登录注册Presenter  邮箱登录失败" + String.valueOf(e), this.getClass());
                                    ToastColorfulUtils.error("登录失败,请重新登录");
                                }
                            }
                        });
                    } else {
                        LogUtils.d("----登录注册Presenter  邮箱登录失败" + String.valueOf(e), this.getClass());
                        ToastColorfulUtils.info("邮箱不存在");
                    }
                }
            });
        }
    }

    public void register(int type, String phone, String code, String email, String username, String pwd,
                         final Button register, final ProgressBar progressbar) {
        if (type == BRTQConstant.LOGIN_LAYOUT_REGISTER) {
            if (phone != null && !FormatUtils.isPhone(phone)) {
                ToastColorfulUtils.error("手机号格式错误");
                setViewVisible(register, progressbar);
                return;
            }
            if (code != null && !FormatUtils.isCheckCode(code)) {
                ToastColorfulUtils.error("验证码格式错误");
                setViewVisible(register, progressbar);
                return;
            }
        }
        if (type == BRTQConstant.LOGIN_LAYOUT_REGISTER_EMAIL) {
            if (email != null && (!FormatUtils.isEmail(email) || email.length() > 31)) {
                ToastColorfulUtils.error("邮箱格式错误");
                setViewVisible(register, progressbar);
                return;
            }
        }
        if (username != null && !FormatUtils.isUserName(username)) {
            ToastColorfulUtils.error("用户名应为3-12个数字、字母或汉字");
            setViewVisible(register, progressbar);
            return;
        }
        if (pwd != null && !FormatUtils.isPassword(pwd)) {
            ToastColorfulUtils.error("密码应为6-12个数字或字母");
            setViewVisible(register, progressbar);
            return;
        }
        if (type == BRTQConstant.LOGIN_LAYOUT_REGISTER) {
            checkCode(phone, code);
            userSignUp(phone, "", username, pwd, register, progressbar);
        }
        if (type == BRTQConstant.LOGIN_LAYOUT_REGISTER_EMAIL) {
            userSignUp("", email, username, pwd, register, progressbar);
        }
    }

    /**
     * 邮箱重置用户密码
     *
     * @param email
     */
    public void resetPwdByEmail(final String email) {
        if (FormatUtils.isEmail(email)) {
            BmobUser.resetPasswordByEmail(email, new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        LogUtils.d("----登录注册Presenter  邮箱重置密码请求成功，请到" + email + "邮箱进行密码重置操作", this.getClass());
                        ToastColorfulUtils.info("邮箱重置密码请求成功，请到" + email + "邮箱进行密码重置操作");
                        // TODO: 2019/3/31 暂时保存当前密码，不断查询当前密码 若不同则表示修改成功

                    } else {
                        LogUtils.d("----登录注册Presenter  邮箱重置密码失败" + String.valueOf(e), this.getClass());
                        ToastColorfulUtils.error("未查询到输入的邮箱地址");
                    }
                }
            });
        } else {
            ToastColorfulUtils.info("请输入正确的邮箱地址");
        }
    }

    /**
     * 手机验证重置密码
     *
     * @param resetPwd
     */
    public void resetPwdByPhone(final String resetPwd) {
        User user = BmobUser.getCurrentUser(User.class);
        if (user != null) {
            user.setPassword(resetPwd);
            user.update(user.getObjectId(), new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        LogUtils.d("----登录注册Presenter  手机重置密码成功", this.getClass());
                        ToastColorfulUtils.success("手机重置密码成功");
                    } else {
                        LogUtils.d("----登录注册Presenter  手机重置密码失败" + String.valueOf(e), this.getClass());
                        ToastColorfulUtils.error("手机重置密码失败");
                    }
                }
            });
        }else {
            ToastColorfulUtils.info("用户未登录,请先登录");
        }
    }

    /**
     * 用户手机或邮箱注册具体实现
     *
     * @param phone
     * @param email
     * @param username
     * @param pwd
     * @param register
     * @param progressbar
     */
    public void userSignUp(String phone, String email, String username, String pwd, final Button register, final ProgressBar progressbar) {
        User user = new User();
        if (phone != null && !phone.equals("")) {
            user.setMobilePhoneNumber(phone);
        }
        if (email != null && !email.equals("")) {
            user.setEmail(email);
        }
        user.setUsername(username);
        user.setPassword(pwd);
        user.signUp(new SaveListener<User>() {
            @Override
            public void done(User user, BmobException e) {
                register.setVisibility(View.VISIBLE);
                progressbar.setVisibility(View.GONE);
                if (e == null) {
                    ToastColorfulUtils.success("注册成功");
                    LogUtils.d("----登录注册Presenter  注册成功" + user.getObjectId(), this.getClass());
                    startToUserCenter(register, progressbar);
                } else {
                    ToastColorfulUtils.error("注册失败");
                    LogUtils.d("----登录注册Presenter  注册失败" + String.valueOf(e), this.getClass());
                }
            }
        });
    }

    /**
     * 登录或注册成功后跳转到用户中心界面，隐藏progressbar
     *
     * @param btn
     * @param progressbar
     */
    public void startToUserCenter(Button btn, final ProgressBar progressbar) {
        progressbar.postDelayed(new Runnable() {
            @Override
            public void run() {
                CircularAnim.fullActivity(loginActivity, progressbar)
                        .go(new CircularAnim.OnAnimationEndListener() {
                            @Override
                            public void onAnimationEnd() {
                                loginActivity.startActivity(new Intent(loginActivity, UserCenterActivity.class));
                                loginActivity.finish();
                            }
                        });
            }
        }, 500);
    }

    /**
     * 显示button, 隐藏progressbar
     *
     * @param button
     * @param progressBar
     */
    private void setViewVisible(Button button, ProgressBar progressBar) {
        button.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
    }

    /**
     * 发送验证码给后台验证，BmobUser默认一个人
     */
    public void checkCode(final String phone, final String code) {
        BmobSMS.verifySmsCode(phone, code, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    LogUtils.d("----登录注册Presenter  短信验证码正确", this.getClass());
                    ToastColorfulUtils.success("短信验证码正确");
                } else {
                    LogUtils.d("----登录注册Presenter  短信验证码错误" + String.valueOf(e), this.getClass());
                    ToastColorfulUtils.error("短信验证码错误");
                }
            }
        });
    }

    /**
     * 判断手机号是否注册
     *
     * @param phone
     */
    public void phoneIsRegister(String phone) {
        BmobQuery<User> query = new BmobQuery<User>();
        query.addWhereEqualTo("mobilePhoneNumber", phone);
        query.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> object, BmobException e) {
                if (e == null && null != object && object.size() != 0) {
                    LogUtils.d("----登录注册Presenter  手机已注册", this.getClass());
                    ToastColorfulUtils.info("手机已注册");
                } else {
                    LogUtils.d("----登录注册Presenter  手机未注册" + String.valueOf(e), this.getClass());
                    ToastColorfulUtils.info("手机未注册");
                }
            }
        });
    }

    /**
     * 判断邮箱是否注册
     *
     * @param email
     */
    public void emailIsRegister(String email, final RoundedImageView mLoginAnimImage) {
        BmobQuery<User> query = new BmobQuery<User>();
        query.addWhereEqualTo("email", email);
        query.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> object, BmobException e) {
                if (e == null && null != object && object.size() != 0) {
                    LogUtils.d("----登录注册Presenter  邮箱已注册", this.getClass());
                    ToastColorfulUtils.info("邮箱已注册");
                    if (object.get(0).getHeadImg() != null && object.get(0).getHeadImg().getFileUrl() != null) {
                        Glide.with(loginActivity).load(object.get(0).getHeadImg().getFileUrl()).
                                placeholder(R.mipmap.detach_male).into(mLoginAnimImage);
                    } else {
                        Glide.with(loginActivity).load(R.mipmap.detach_male).into(mLoginAnimImage);
                    }
                } else {
                    LogUtils.d("----登录注册Presenter  邮箱未注册" + String.valueOf(e), this.getClass());
                    ToastColorfulUtils.info("邮箱未注册");
                    Glide.with(loginActivity).load(R.mipmap.detach_male).into(mLoginAnimImage);
                }
            }
        });
    }

    /**
     * 判断用户名是否注册
     *
     * @param name
     */
    public void nameIsRegister(String name, final RoundedImageView mLoginAnimImage) {
        BmobQuery<User> query = new BmobQuery<User>();
        query.addWhereEqualTo("username", name);
        query.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> object, BmobException e) {
                if (e == null && null != object && object.size() > 0) {
                    LogUtils.d("----登录注册Presenter  该用户名已注册", this.getClass());
                    LogUtils.d("----登录注册Presenter  该用户头像：" + object.get(0).getHeadImg().getFileUrl());
                    ToastColorfulUtils.info("该用户名已注册");
                    if (object.get(0).getHeadImg() != null && object.get(0).getHeadImg().getFileUrl() != null) {
                        Glide.with(loginActivity).load(object.get(0).getHeadImg().getFileUrl()).
                                placeholder(R.mipmap.detach_male).into(mLoginAnimImage);
                    } else {
                        Glide.with(loginActivity).load(R.mipmap.detach_male).into(mLoginAnimImage);
                    }
                } else {
                    LogUtils.d("----登录注册Presenter  该用户名未注册" + String.valueOf(e), this.getClass());
                    ToastColorfulUtils.info("该用户名未注册");
                    Glide.with(loginActivity).load(R.mipmap.detach_male).into(mLoginAnimImage);
                }
            }
        });
    }

}
